/**
 * Copyright 2020 Tianshu AI Platform. All Rights Reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================
 */
package com.zkyc.framework.schedulejob.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.pojo.Pi;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.UploadVo;
import com.zkyc.framework.schedulejob.client.FileClient;
import com.zkyc.framework.schedulejob.constant.UrlConstant;
import com.zkyc.framework.common.mapper.PiMapper;
import com.zkyc.framework.common.service.RestTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;


/**
 * @description 定时拉取PI文件
 */
@Slf4j
@Component
@RefreshScope
public class PITask {
    @Autowired
    private FileClient fileClient;

    @Autowired
    RestTemplateService restTemplateService;

    @Autowired
    private PiMapper piMapper;

    @Value("${zjlab.cookie}")
    private String cookies;

    public static final String PI_BASIC = "http://gateway.dmind.zhejianglab.com/rest/davinci-0.3-rc/api/v3/zj/34/fetchData";
    public static final String PI_RESEARCH = "http://gateway.dmind.zhejianglab.com/rest/davinci-0.3-rc/api/v3/zj/35/fetchData";


    /**
     * 每天晚上12点定时拉取PI数据
     */
    //@Scheduled(cron = "*/20 * * * * ?")
    @Scheduled(cron = "0 0 0 * * ?")
    public void process() {
        //这里是和中心关联的代码
/*        List<String> userCodeList = piMapper.getUserCodeList();
        userCodeList.forEach(userCodes -> {
            String[] userCodesSplit = userCodes.split(",");
            for (String userCode : userCodesSplit) {
                userCodeSet.add(userCode);
            }
        });
        */
        List<String> userCodeList = piMapper.getAllUserCodeList();
        HashSet<String> userCodeSet = new HashSet<String>();
        userCodeList.forEach(userCode -> {
            userCodeSet.add(userCode);

        });
        for (String userCode : userCodeSet) {
            HashMap<String, String> map = new HashMap();
            map.put("userCode", userCode);
            PITask(map);
        }
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("PI执行了");
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("----------------------");
        System.out.println("----------------------");
    }

    @Async
    public void PITask(HashMap<String, String> map) {
        JSONObject userCodeJSON = new JSONObject();
        userCodeJSON.put("user_code", map.get("userCode"));
        //调用PI_BASIC接口
        String piBasicString = HttpRequest.get(PI_BASIC)
                .form("user_code", map.get("userCode"))
                .execute().body();
        //调用PI_RESEARCH接口
        String piBasicResearch = HttpRequest.get(PI_RESEARCH)
                .form("user_code", map.get("userCode"))
                .execute().body();
        //处理数据
        JSONObject piBasicJsonOriginal = JSONObject.parseObject(piBasicString);
        JSONObject piResearchJsonOriginal = JSONObject.parseObject(piBasicResearch);
        JSONArray piBasicArray = piBasicJsonOriginal.getJSONObject("payload").getJSONArray("resultList");
        JSONArray piResearchArray = piResearchJsonOriginal.getJSONObject("payload").getJSONArray("resultList");
        if (piBasicArray.size() > 0) {
            JSONObject piBasicJSONObject = piBasicArray.getJSONObject(NumberConstant.NUMBER_0);
            //下载头像存储至Minio
            //setPhoto(piBasicJSONObject);
            //JSONObject piResearchJSONObject = piResearchArray.getJSONObject(NumberConstant.NUMBER_0);
            piBasicArray.add(piResearchArray);
        }
        QueryWrapper<Pi> queryWrapper = new QueryWrapper<>();
        if (map.get("userCode") != null) {
            String userCode = map.get("userCode");
            queryWrapper.eq("user_code", userCode);
            List<Pi> piList = piMapper.selectList(queryWrapper);
            if (piList.size() == 0) {
                Pi pi = new Pi();
                pi.setIsVerified(NumberConstant.NUMBER_0);
                pi.setUserCode(userCode);
                pi.setPiInformation(piBasicArray.toString().replaceAll("https://file.zhejianglab.com","https://www.zhejianglab.com"));
                setInformation(piBasicArray, pi);
                pi.setCreateUserName("superadmin");
                piMapper.insert(pi);
                //log.info("pi添加成功:{}", pi);
            } else {
                piList.forEach(pi -> {
                    pi.setPiInformation(piBasicArray.toString().replaceAll("https://file.zhejianglab.com","https://www.zhejianglab.com"));
                    setInformation(piBasicArray, pi);
                    piMapper.updateById(pi);
                });
                //log.info("pi更新成功:{}", pi);
            }
        }
    }

    private void setInformation(JSONArray piBasicArray, Pi pi) {
        if (piBasicArray.size() > 0) {
            pi.setName(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("name").toString());
            pi.setOrganizationTwo(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("dept_name", " ").toString());
            pi.setOrganizationOne(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("ssbm", " ").toString());
            String photo = piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("photo", " ").toString();
            pi.setPhoto(photo.replaceAll("https://file.zhejianglab.com","https://www.zhejianglab.com"));
            pi.setPosition(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("zw", " ").toString());
            //设置介绍
            JSONArray jsonArray = piBasicArray.getJSONArray(NumberConstant.NUMBER_1);
            for (int i = 0; i < jsonArray.size(); i++) {
                String introduce = "";
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (StringUtils.isNotBlank(jsonObject.get("content").toString())) {
                    introduce += jsonObject.get("name").toString() + ": " + jsonObject.get("content").toString() + ";<br/>";
                }
                if (introduce.length() > 6) {
                    pi.setIntroduce(introduce.substring(0, introduce.length() - 6));
                } else {
                    pi.setIntroduce(introduce);
                }
            }
        }
    }

    private void setPhoto(JSONObject piBasicJSONObject) {
        if (piBasicJSONObject.get("photo") != null) {
            String photo = piBasicJSONObject.get("photo").toString();
            try {
                UploadVo uploadVo = fileClient.uploadByUrl(photo, StringPool.ONE);
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(uploadVo.getData()));
                piBasicJSONObject.put("photo", jsonObject.get("url"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}